const express = require('express')
const router = express.Router()
const { User, PointsTransaction } = require('../models')
const auth = require('../middleware/auth')
const logger = require('../utils/logger')

/**
 * @api {get} /api/users/profile 获取用户信息
 * @apiDescription 获取当前登录用户的详细信息
 * @apiName GetUserProfile
 * @apiGroup Users
 * @apiHeader {String} Authorization 用户token
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 用户信息
 */
router.get('/profile', auth, async (req, res) => {
  try {
    const userId = req.user.id

    const user = await User.findByPk(userId, {
      attributes: [
        'id', 'phone', 'nickname', 'avatar', 'gender', 'birthday',
        'points', 'member_level', 'invitation_code', 'role', 'status', 'created_at'
      ]
    })

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    // 获取邀请人信息
    let inviter = null
    if (user.inviter_id) {
      inviter = await User.findByPk(user.inviter_id, {
        attributes: ['id', 'nickname', 'avatar']
      })
    }

    // 获取邀请数量
    const inviteCount = await User.count({
      where: { inviter_id: userId }
    })

    res.json({
      success: true,
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        gender: user.gender,
        birthday: user.birthday,
        points: user.points,
        memberLevel: user.member_level,
        invitationCode: user.invitation_code,
        role: user.role,
        status: user.status,
        createdAt: user.created_at,
        inviter: inviter,
        inviteCount: inviteCount
      }
    })
  } catch (error) {
    logger.error('Get user profile error:', error)
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    })
  }
})

/**
 * @api {put} /api/users/profile 更新用户信息
 * @apiDescription 更新当前登录用户的信息
 * @apiName UpdateUserProfile
 * @apiGroup Users
 * @apiHeader {String} Authorization 用户token
 * @apiParam {String} nickname 昵称
 * @apiParam {String} avatar 头像URL
 * @apiParam {Number} gender 性别: 0-未知, 1-男, 2-女
 * @apiParam {String} birthday 生日(YYYY-MM-DD)
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 更新后的用户信息
 */
router.put('/profile', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { nickname, avatar, gender, birthday } = req.body

    const user = await User.findByPk(userId)
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    // 更新用户信息
    const updateData = {}
    if (nickname) updateData.nickname = nickname
    if (avatar) updateData.avatar = avatar
    if (gender !== undefined) updateData.gender = gender
    if (birthday) updateData.birthday = birthday

    await user.update(updateData)

    res.json({
      success: true,
      message: '用户信息更新成功',
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        gender: user.gender,
        birthday: user.birthday,
        points: user.points,
        memberLevel: user.member_level,
        invitationCode: user.invitation_code
      }
    })
  } catch (error) {
    logger.error('Update user profile error:', error)
    res.status(500).json({
      success: false,
      message: '更新用户信息失败'
    })
  }
})

/**
 * @api {put} /api/users/password 修改密码
 * @apiDescription 修改当前登录用户的密码
 * @apiName UpdatePassword
 * @apiGroup Users
 * @apiHeader {String} Authorization 用户token
 * @apiParam {String} oldPassword 旧密码
 * @apiParam {String} newPassword 新密码
 * @apiSuccess {Boolean} success 是否成功
 */
router.put('/password', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { oldPassword, newPassword } = req.body

    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '旧密码和新密码不能为空'
      })
    }

    const user = await User.findByPk(userId)
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    // 验证旧密码
    const isPasswordValid = await user.verifyPassword(oldPassword)
    if (!isPasswordValid) {
      return res.status(400).json({
        success: false,
        message: '旧密码错误'
      })
    }

    // 更新密码
    await user.update({ password: newPassword })

    res.json({
      success: true,
      message: '密码修改成功'
    })
  } catch (error) {
    logger.error('Update password error:', error)
    res.status(500).json({
      success: false,
      message: '修改密码失败'
    })
  }
})

/**
 * @api {put} /api/users/bind-phone 绑定手机号
 * @apiDescription 为微信登录用户绑定手机号
 * @apiName BindPhone
 * @apiGroup Users
 * @apiHeader {String} Authorization 用户token
 * @apiParam {String} phone 手机号
 * @apiParam {String} verifyCode 验证码
 * @apiSuccess {Boolean} success 是否成功
 */
router.put('/bind-phone', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { phone, verifyCode } = req.body

    if (!phone || !verifyCode) {
      return res.status(400).json({
        success: false,
        message: '手机号和验证码不能为空'
      })
    }

    // 验证码校验(实际项目中需要实现)
    if (verifyCode !== '1234') {
      return res.status(400).json({
        success: false,
        message: '验证码错误'
      })
    }

    // 检查手机号是否已被其他用户绑定
    const existingUser = await User.findOne({
      where: { phone }
    })

    if (existingUser && existingUser.id !== userId) {
      return res.status(400).json({
        success: false,
        message: '该手机号已被其他用户绑定'
      })
    }

    const user = await User.findByPk(userId)
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    // 更新手机号
    await user.update({ phone })

    res.json({
      success: true,
      message: '手机号绑定成功',
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar
      }
    })
  } catch (error) {
    logger.error('Bind phone error:', error)
    res.status(500).json({
      success: false,
      message: '绑定手机号失败'
    })
  }
})

/**
 * @api {get} /api/users/points 获取用户积分
 * @apiDescription 获取当前登录用户的积分信息
 * @apiName GetUserPoints
 * @apiGroup Users
 * @apiHeader {String} Authorization 用户token
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 积分信息
 */
router.get('/points', auth, async (req, res) => {
  try {
    const userId = req.user.id

    const user = await User.findByPk(userId, {
      attributes: ['id', 'points']
    })

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      })
    }

    // 获取最近的积分记录
    const recentRecords = await PointRecord.findAll({
      where: { user_id: userId, status: 1 },
      order: [['created_at', 'DESC']],
      limit: 5
    })

    // 格式化积分记录
    const records = recentRecords.map(record => ({
      id: record.id,
      points: record.points,
      balance: record.balance,
      type: record.type,
      description: record.description,
      createdAt: record.created_at
    }))

    res.json({
      success: true,
      data: {
        points: user.points,
        recentRecords: records
      }
    })
  } catch (error) {
    logger.error('Get user points error:', error)
    res.status(500).json({
      success: false,
      message: '获取用户积分失败'
    })
  }
})

module.exports = router